/* eslint-disable camelcase */
import {STRING} from 'oneutil'
import wxs_behavior from './behavior/wxs_behavior'
import wx from './wx'

export default function OnekitComponent(wx_object) {
  const properties = {}
  const my_object = {
    mixins: [wxs_behavior],
    data() {
      ''
    },
    onInit(query) {
      let created
      if (wx_object.lifetimes && wx_object.lifetimes.created) {
        created = wx_object.lifetimes.created
      } else if (wx_object.created) {
        created = wx_object.created
      } else {
        created = function () { }
      }
      created.call(this, query)
    },
    didMount() {
      for (const k of Object.keys(this.props)) {
        const v = this.props[k]
        properties[k] = v
        this.data[k] = v
      }
      let attached
      if (wx_object.lifetimes && wx_object.lifetimes.attached) {
        attached = wx_object.lifetimes.attached
      } else if (wx_object.attached) {
        attached = wx_object.attached
      } else {
        attached = function () { }
      }
      attached.call(this)
      // //////
      let ready
      if (wx_object.lifetimes && wx_object.lifetimes.ready) {
        ready = wx_object.lifetimes.ready
      } else if (wx_object.ready) {
        ready = wx_object.ready
      } else {
        ready = function () { }
      }
      ready.call(this)
    },
    didUnmount() {
      let detached
      if (wx_object.lifetimes && wx_object.lifetimes.detached) {
        detached = wx_object.lifetimes.detached
      } else if (wx_object.detached) {
        detached = wx_object.detached
      } else {
        detached = function () { }
      }
      detached.call(this)
    },
    methods: {
      get properties() {
        return properties
      },

    }
  }
  if (wx_object) {
    if (!wx_object.methods) { wx_object.methods = {} }
    wx_object.methods.triggerEvent = function (name, data) {
      const funcName = `on${STRING.firstUpper(name)}`
      if (this.props[funcName]) {
        this.props[funcName](data)
      }
    }
    wx_object.methods.createSelectorQuery = wx.createSelectorQuery
  }
  for (const key of Object.keys(wx_object)) {
    const value = wx_object[key]
    if (!value) {
      continue
    }
    switch (key) {
      case 'properties':
        my_object.props = {}
        for (const k of Object.keys(value)) {
          const p = value[k]
          const v = (p && p.value ? p.value : null)
          my_object.props[k] = v
          properties[k] = v
        }
        break
      case 'methods':
        for (const k of Object.keys(value)) {
          my_object.methods[k] = value[k]
        }
        break
      case 'data':
        for (const k of Object.keys(value)) {
          my_object.data[k] = value[k]
        }
        break
      case 'behaviors':
        my_object.mixins = value
        break
      default:
        my_object[key] = value
        break
    }
  }
  return Component(my_object)
}
